<template>
  <el-card class="box-card">
    <el-tabs type="border-card">


      <el-tab-pane label="个人信息">
        <span slot="label"><i class="el-icon-info"></i> 个人信息 </span>
        <el-form :model="userForm" :rules="formRules" ref="userFrom" label-width="100px">

          <el-form-item label="头像" prop="headPortrait">
            <my-upload-img ref="upload"
                            @file-selected="handleFileSelected"
                            @image-removed="handleImageRemoved"
                            :imageUrl="userForm.headPortrait"
            />
          </el-form-item>

          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" :disabled="true"></el-input>
          </el-form-item>

          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="userForm.nickname"></el-input>
          </el-form-item>

          <el-form-item label="个人简介" prop="introduce">
            <el-input v-model="userForm.introduce" type="textarea"></el-input>
          </el-form-item>

          <el-form-item label="个人邮箱" prop="email">
            <el-input v-model="userForm.email"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="updateUserInfo('userFrom')">修改</el-button>
            <el-button @click="resetForm('userFrom')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>


      <el-tab-pane label="修改密码">
        <span slot="label"><i class="el-icon-warning"></i> 修改密码 </span>
        <el-form :model="passwordForm" :rules="formRules" ref="passwordForm" label-width="100px">

          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="passwordForm.oldPassword" type="password"></el-input>
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordForm.newPassword" type="password"></el-input>
          </el-form-item>

          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input v-model="passwordForm.confirmPassword" type="password"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="updatePassword('passwordForm')">修改</el-button>
            <el-button @click="resetForm('passwordForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>


    </el-tabs>
  </el-card>
</template>

<script>
import { settingApi } from '@/api';

export default {
  name: "Setting",
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    return {
      userForm: {
        id: this.$store.state.userId,
        username: this.$store.state.username,
        nickname: this.$store.state.nickname,
        email: this.$store.state.email,
        headPortrait: this.$store.state.headPortrait,
        introduce: this.$store.state.introduce,
      },
      passwordForm: {},
      selectedFile: null,
      formRules: {
        username: [
          {required: true, message: '请输入用户名称', trigger: 'blur'}
        ],
        oldPassword: [
          {required: true, message: '请输入原密码', trigger: 'blur'}
        ],
        newPassword: [
          {required: true, message: '请输入新密码', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, validator: validatePass, trigger: 'blur'}
        ],
      },
    }


  },


  methods: {
    /**
     * 处理文件选择
     */
    handleFileSelected(file) {
      this.selectedFile = file;
    },

    /**
     * 处理图片移除
     */
    handleImageRemoved() {
      this.selectedFile = null;
      this.userForm.headPortrait = '';
    },

    // 重置弹出框内容
    resetForm(formName) {
      if (formName === 'userFrom') {
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
        this.selectedFile = null;
        // 保留从store中获取的原始数据
        this.userForm = {
          id: this.$store.state.userId,
          username: this.$store.state.username,
          nickname: this.$store.state.nickname,
          email: this.$store.state.email,
          headPortrait: this.$store.state.headPortrait,
          introduce: this.$store.state.introduce,
        };
      } else if (formName === 'passwordForm') {
        this.passwordForm = {};
      }
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },

    /**
     * 修改用户信息
     * @param formName
     */
    updateUserInfo(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formData = new FormData();
          // 添加普通表单字段
          formData.append('id', this.userForm.id);
          formData.append('nickname', this.userForm.nickname);
          formData.append('email', this.userForm.email);
          formData.append('introduce', this.userForm.introduce);
          // 添加文件字段
          if (this.selectedFile) {
            formData.append('headPortraitFile', this.selectedFile);
          }

          settingApi.updateUserInfo(formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then((response) => {
            if (response.data.code === 20000) {
              // 更新store中的用户信息
              this.$store.commit("updateUserInfo", this.userForm);
              // 重置上传状态
              this.selectedFile = null;
              if (this.$refs.upload) {
                this.$refs.upload.clearFiles();
              }
              this.$message({
                showClose: true,
                message: '操作成功！',
                type: 'success',
              });
            }
          }).catch(error => {
            this.$message({
              showClose: true,
              message: '操作失败：' + (error.response?.data?.message || '未知错误'),
              type: 'error',
            });
          });
        }
      });
    },

    /**
     * 修改密码
     * @param formName
     */
    updatePassword(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = this.passwordForm;
          settingApi.updatePassword(data).then((response) => {
            if (response.data.code === 20000) {
              this.$message({
                showClose: true,
                message: '更新成功！',
                type: 'success',
              });
              this.passwordForm = {};
              this.$refs[formName].resetFields();
            }
          }).catch(error => {
            this.$message({
              showClose: true,
              message: '操作失败：' + (error.response?.data?.message || '未知错误'),
              type: 'error',
            });
          });
        }
      });
    },

  }
}
</script>

<style scoped>
.el-input {
  width: 200px;
}

.el-tab-pane {
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>
